// pages/celiang/celiang.js

var utilBT = require('../../js/utilBT.js');
var utilData = require('../../js/utilData.js');
var api = require('../../js/api.js');

const app = getApp()
var data = new Array()
var t0 = 0
// var user_id = 0;
let ui = {}
Page({

    /**
     * 页面的初始数据
     */
    data: {

        hasToken: false,
        sn: 100,
        test_start: false,
        interval_num: '',
        show: false,

        // modalHidden1: true,
        modalHidden2: true,

        users: [],

        vouis: {},

        userIndex: 0,

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        var that = this
        that.setData({
            users: app.globalData.users,
            hasToken: app.globalData.head.hasToken,
        })


        api.checkToken().then(b => {
            if (b) {
                that.upd_top_user()
            }
        })


        const query = wx.createSelectorQuery().select('#canvas0')
            .fields({node: true, size: true})
            .exec((res) => {
                // app.log(res)
                const canvas = res[0].node

                const ctx = canvas.getContext('2d')

                canvas.width = 1000;
                canvas.height = 800;
                ctx.clearRect(0, 0, 1000, 800);

                let x = 500
                let y = 500
                let r1 = 280
                let r2 = 320
                let w1 = 25
                let w2 = 5


                var grd = ctx.createLinearGradient(200, 200, 800, 800);
                grd.addColorStop("0", "#F99F60");
                grd.addColorStop("1", "#F08325");

                ctx.beginPath()
                ctx.arc(x, y, r1, -5 / 4 * Math.PI, 1 / 4 * Math.PI, false)
                ctx.strokeStyle = grd
                ctx.lineWidth = w1
                ctx.setLineDash([5, 10])
                ctx.stroke()
                ctx.closePath()

                ctx.beginPath()
                ctx.arc(x, y, r2, -5 / 4 * Math.PI, 1 / 4 * Math.PI, false)
                ctx.strokeStyle = '#90E5D1'
                ctx.lineWidth = w2
                ctx.setLineDash([])
                ctx.stroke()
                ctx.closePath()

            })


    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        that.setData({
            sn: app.globalData.BLE_SN,
        })
        that.canvas0Draw(75)

        that.onGetData()


    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.unGetData()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        // this.onShow()
        // utilBT.connToDid()
        //当逻辑执行完后关闭刷新
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    onGetData: function () {
        var that = this
        wx.onBLECharacteristicValueChange(function (res) {
            app.log('====>>' + app.globalData.equ.name + '接收到的数据')
            utilData.deData(res, function (res) {
                if (res.code == 4) {
                    app.log('==>>尿检结果如下')
                    app.log(res.ur)

                    ui = res.ur

                    ui.userId = app.globalData.userId
                    // ui.wxInfoId = app.globalData.users[app.globalData.usersIndex].wxInfoId
                    ui.bluetoothMac = app.globalData.equ.mac

                    if (JSON.stringify(ui).length > 110) {

                        app.log('==>>打开弹窗')
                        that.setData({
                            modalHidden2: false
                        })


                    }

                } else if (res.code == 5) {
                    app.log('==>>读取全部数据')
                    let t1 = new Date().getTime()
                    app.log(t1 - t0)

                } else if (res.code == 7) {
                    app.log('==>>错误响应')
                    wx.showModal({
                        title: '出现错误！',
                        content: res.err_msg,
                        showCancel: false,
                        success(res) {
                            if (res.confirm) {
                                app.log('====>>token过期，用户点击确定')
                            } else if (res.cancel) {
                                app.log('====>>token过期，用户点击取消')
                            }
                            clearInterval(that.data.interval_num)
                            that.canvas0Draw(75)
                            that.setData({
                                test_start: false,
                            })
                        }
                    })
                }

            })

            if (that.data.sn == 100) {
                that.setData({
                    sn: app.globalData.BLE_SN,
                })
            }

        })


        if (app.globalData.BLE_SN == 701 || app.globalData.BLE_SN == 705) {

            that.send_code('02')
        }


    },
    unGetData: function () {
        wx.offBLECharacteristicValueChange(function (res) {

            app.log('====>>取消监听蓝牙数据')
            app.log(res)
        })
    },

    get_value: function (e) {
        var that = this
        if (app.globalData.BLE_SN == 100) {
            that.setData({
                sn: 100
            })
        } else {
            let code = e.currentTarget.dataset['code'];
            app.log('==>>code:' + code)


            if (code == '0B') {

                wx.showModal({
                    title: '请确认已放置好试纸',
                    showCancel: true,
                    success(res) {
                        if (res.confirm) {
                            app.log('====>>用户点击确定')
                            that.send_code(code)

                            that.setData({
                                test_start: true
                            })
                            that.count_down(75)

                        } else if (res.cancel) {
                            app.log('====>>用户点击取消')
                        }
                    }
                })

            } else {
                that.send_code(code)
                clearInterval(that.data.interval_num)
                that.setData({
                    test_start: false,
                    // interval_num: 999,
                })
                that.canvas0Draw(75)
            }


        }


    },
    send_code: function (code) {
        if (app.globalData.equconn0) {
            utilData.get_code(code, function (code) {
                utilBT.sendHex(code, function (data) {

                    app.log('====>>back:')
                    app.log(data)

                })
            })

        }
    },
    count_down: function (num) {
        var that = this
        that.data.interval_num = setInterval(function () {
            // app.log('==>>num:' + num)
            if (num > 0) {
                num--
                that.canvas0Draw(num)
            }

        }, 1000)
    },
    canvas0Draw: function (second) {

        var that = this

        let num = Math.abs(second - 75)
        let per = Math.round(num * 100 / 75)
        if (that.data.test_start > 0) {
            // wx.hideTabBar()
            that.setData({
                show: true
            })

        }
        let msg = '未连接'
        if (that.data.hasToken) {
            msg = '等待测试'
            if (num > 0 && num < 75) {
                msg = '测试中'
            } else if (num >= 75) {
                msg = '测试完成'
            }
        }

        const query = wx.createSelectorQuery().select('#canvas1')
            .fields({node: true, size: true})
            .exec((res) => {
                // app.log('==>>||'+res)
                const canvas = res[0].node

                const ctx = canvas.getContext('2d')

                canvas.width = 1000;
                canvas.height = 800;
                ctx.clearRect(0, 0, 1000, 800);


                ctx.beginPath()
                ctx.font = '100px Defult'
                ctx.fillStyle = '#FFF'
                ctx.textAlign = 'center'
                ctx.fillText(per + '%', 500, 530)
                ctx.closePath()

                ctx.beginPath()
                ctx.font = '45px Defult'
                ctx.fillStyle = '#FFF'
                ctx.textAlign = 'center'
                ctx.fillText(msg, 500, 630)
                ctx.closePath()


                let x = 500
                let y = 500
                let r1 = 280
                let r2 = 320
                let w1 = 25
                let w2 = 8
                let w3 = 20


                // ctx.beginPath()
                // ctx.arc(x, y, r, 0 * Math.PI, 2 * Math.PI, false)
                // ctx.strokeStyle = '#5CADFE'
                // ctx.lineWidth = w1
                // ctx.setLineDash([5, 10])
                // ctx.stroke()
                // ctx.closePath()

                ctx.beginPath()
                ctx.arc(x, y, r1, (0 - 5 / 4) * Math.PI, (num / 75 * 6 / 4 - 5 / 4) * Math.PI, false)
                ctx.strokeStyle = '#FFF'
                ctx.lineWidth = w1
                ctx.setLineDash([5, 10])
                ctx.stroke()
                ctx.closePath()


                ctx.beginPath()
                ctx.arc(x, y, r2, (0 - 5 / 4) * Math.PI, (num / 75 * 6 / 4 - 5 / 4) * Math.PI, false)
                ctx.strokeStyle = '#FFF'
                ctx.lineCap = 'round'
                ctx.lineWidth = w2
                ctx.setLineDash([])
                ctx.stroke()
                ctx.closePath()


                ctx.beginPath()
                ctx.arc(x, y, r2, ((num - 0.1) / 75 * 6 / 4 - 5 / 4) * Math.PI, (num / 75 * 6 / 4 - 5 / 4) * Math.PI, false)
                ctx.strokeStyle = '#FFF'
                ctx.lineCap = 'round'
                ctx.lineWidth = w3
                ctx.setLineDash([])
                ctx.stroke()
                ctx.closePath()


            })
    },
    ex_values: function (e) {
        var that = this
        if (app.globalData.BLE_SN == 100) {
            that.setData({
                sn: 100
            })
        } else {
            let code = e.currentTarget.dataset['code'];
            app.log('==>>code:' + code)

            t0 = new Date().getTime()

            that.send_code(code)
            wx.showLoading({
                title: '正在导出数据...',
                mask: true,
            })
            setTimeout(function () {
                wx.hideLoading()
                wx.showLoading({
                    title: '正在生成文档...',
                    mask: true,
                })
                setTimeout(() => {
                    wx.hideLoading()
                }, 5000)
                if (app.globalData.urs_all.length > 0) {
                    api.exPortUis(JSON.stringify(app.globalData.urs_all)).then(res => {
                        const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
                        fs.writeFile({
                            filePath: wx.env.USER_DATA_PATH + "/" + that.data.sn + "全部数据.xlsx", // wx.env.USER_DATA_PATH 指定临时文件存入的路径，后面字符串自定义
                            data: res.data,
                            encoding: "binary", //二进制流文件必须是 binary
                            success(res) {
                                wx.hideLoading()
                                wx.openDocument({ // 打开文档
                                    filePath: wx.env.USER_DATA_PATH + "/" + that.data.sn + "全部数据.xlsx",  //拿上面存入的文件路径
                                    showMenu: true, // 显示右上角菜单
                                    success: function (res) {
                                        // setTimeout(()=>{wx.hideLoading()},500)
                                    }
                                })
                            }
                        })
                    })
                }
            }, 8000)
        }
    },
    toShebei: function () {
        app.log('====>>toShebei')
        wx.navigateTo({
            url: '/pages/geren/shebei/shebei'
        })
    },


    modalTap2: function (e) {
        app.log('==>>打开弹窗')
        this.setData({
            modalHidden2: false
        })
    },
    modal_n: function () {
        // bindcancel="modal_n"
        app.log('==>>点击取消')
        // this.setData({
        //     modalHidden2: true
        // })
    },
    modal_y: function (e) {
        let that = this
        app.log('==>>点击确定')
        that.setData({
            modalHidden2: true
        })


        clearInterval(that.data.interval_num)
        that.setData({
            test_start: false,
        })
        app.log('========>>')
        let voui = {}
        voui.ur = ui
        voui.ur.userId = app.globalData.users[parseInt(that.data.userIndex)].userId
        wx.navigateTo({
            url: '/pages/pingu/pingu?voui=' + JSON.stringify(voui)+'&usersIndex='+that.data.userIndex
        })
    },


    radioChange(e) {
        let that = this
        app.log('radio发生change事件，携带value值为：', e.detail.value)
        let index = e.detail.value
        app.log('==>>index:' + index)
        that.setData({
            userIndex: index
        })

    },

    upd_top_user: function (e) {
        var that = this
        that.setData({
            users: app.globalData.users
        })
        let userId = app.globalData.users[app.globalData.usersIndex].userId

        api.checkToken().then(b => {
            if (b) {
                that.get_new(userId)
            }

        })
    },
    get_new: function (userId) {

        let that = this

        let dtoui = {}
        let ur = {}
        ur.userId = userId
        dtoui.ur = ur
        dtoui.uis = JSON.stringify(app.globalData.uis)

        api.getNewUiRet(dtoui).then(res => {
            that.setData({
                vouis: res.data.data
            })

        })
    }

})